﻿using System;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Google.YouTube;

namespace YoutubeGetterV2
{
    public static class YoutubeTools
    {
        public static YouTubeRequest request;
        public static String clientID = "Playlist Grabber";
        public static String developerKey = "AI39si40aI5u5-KdeEMIjZ14pDTbNlMzsMjuwpc1s1iiidLqWuTKxHnwXJdO6tR8YNjDuE2gNRzXxeAsq1RA6hbTFlz_ou0Vpw";
        public static String videoUrlID = "http://gdata.youtube.com/feeds/api/videos/{0}";
        public static Int32 currentDownloads = 0;
        private static String videoInfo = "http://www.youtube.com/get_video_info?&video_id={0}&el=embedded&ps=default&eurl=http://boe2.be/";
        private static String videoUrl = "http://www.youtube.com/get_video?t={0}&video_id={1}&fmt={2}&asv=2";

        #region user settings
        public static String downloadLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\YouTube";
        public static Boolean useSubFolders = true;
        public static Int32 maxDownloads = 5;
        #endregion

        #region functions
		public static Video GetVideoByID(String id)
		{
			Uri uri = new Uri(String.Format(videoUrlID, id));
			return request.Get<Video>(uri).Entries.FirstOrDefault();
		}
        public static String GetUrlFromVideoID(String videoID, VideoQuality videoQuality)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(String.Format(videoInfo, videoID));
            webRequest.Timeout = 10000;
            webRequest.UserAgent = "boeboebrowser";
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);
            String responseToken = responseStream.ReadToEnd();
            Regex tokenFilter = new Regex(@"&token=(?<token>[a-zA-Z0-9=_%+-]*)&");
            if (tokenFilter.IsMatch(responseToken))
            {
                responseToken = tokenFilter.Matches(responseToken)[0].Groups["token"].Value;
            }
            else
            {
                // get_video_info doesn't want to give us a token. we will have to get it from the main site (slower!)
                webRequest = (HttpWebRequest)WebRequest.Create(String.Format(@"http://www.youtube.com/watch?v={0}", videoID));
                webRequest.Timeout = 10000;
                webRequest.UserAgent = "boeboebrowser";
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);
                responseToken = responseStream.ReadToEnd();
                tokenFilter = new Regex(@"&t=(?<token>[a-zA-Z0-9=_%+-]*)&");
                if (tokenFilter.IsMatch(responseToken))
                {
                    responseToken = tokenFilter.Matches(responseToken)[0].Groups["token"].Value;
                }
                else
                {
                    return null;
                }
            }
            return String.Format(videoUrl, responseToken, videoID, (Int32)videoQuality);
        }
        #endregion
    }
}
